package com.example.blue;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.blue.ui.DynamicWaveFormView;

import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;


public class OulajiaoActivity extends AppCompatActivity implements DataProcessorManager.DataUpdateListener{
    private static final String TAG = "OulajiaoActivity";
    private String deviceId;
    private Spinner spinner;
    private Integer selectedSensorNum=0;
    private BluetoothService bluetoothService;
    private Boolean isBound=false;
    private DynamicWaveFormView waveformViewX;
    private DynamicWaveFormView waveformViewY;
    private DynamicWaveFormView waveformViewZ;
    private Thread workerThreadx;
    private Thread workerThready;
    private Thread workerThreadz;
    private Boolean runningx=false;
    private Boolean runningy=false;
    private Boolean runningz=false;
    private Handler handler = new Handler(Looper.getMainLooper());
    private DataProcessorManager processorManager;
    private final ConcurrentLinkedQueue<Float> magxDataQueue = new ConcurrentLinkedQueue<>();
    private final ConcurrentLinkedQueue<Float> magyDataQueue = new ConcurrentLinkedQueue<>();
    private final ConcurrentLinkedQueue<Float> magzDataQueue = new ConcurrentLinkedQueue<>();
    private ConcurrentLinkedQueue<byte[]> dataQueue = new ConcurrentLinkedQueue<>();

    private final ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            BluetoothService.LocalBinder binder = (BluetoothService.LocalBinder) service;
            bluetoothService = binder.getService();
            isBound = true;
            Log.d("ServiceTest", "onServiceConnected: bound=" + isBound);
            dataQueue  = bluetoothService.getDataQueue();
//            if(dataQueue.isEmpty()){
//                new AlertDialog.Builder(OulajiaoActivity.this)
//                        .setTitle("提示")
//                        .setMessage("未收到数据，请重试")
//                        .setPositiveButton("确定", (dialog, which) -> {
//                            finish();
//                        })
//                        .show();
//            }else {
                processorManager = DataProcessorManager.getInstance(dataQueue);
                processorManager.setDataUpdateListener(OulajiaoActivity.this);
                processorManager.startProcessing();
                processorManager.setProcessingFunction(ProcessingFunction.Allout);
//            }
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            isBound = false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_oulajiao);
        // 开启返回箭头
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(null);
        getSupportActionBar().setTitle("传感器欧拉角");

        SharedPreferences sp = getSharedPreferences("my_cache", Context.MODE_PRIVATE);
        deviceId = sp.getString("deviceId", "");
        System.out.println(deviceId);
        if (deviceId == "" || deviceId.isEmpty()) {
            Toast.makeText(OulajiaoActivity.this,"未获取到蓝牙MAC地址，请重新连接",Toast.LENGTH_SHORT).show();
        }

        waveformViewX = findViewById(R.id.waveformView1);
        waveformViewY = findViewById(R.id.waveformView2);
        waveformViewZ = findViewById(R.id.waveformView3);
        waveformViewX.setYtitle("X轴欧拉角(deg)");
        waveformViewX.setYRange(-180,180);
        waveformViewY.setYtitle("Y轴欧拉角(deg)");
        waveformViewY.setYRange(-180,180);
        waveformViewZ.setYtitle("Z轴欧拉角(deg)");
        waveformViewZ.setYRange(-180,180);

        spinner = findViewById(R.id.modeSpinner);
        String[] options = {"传感器1", "传感器2", "传感器3", "传感器4", "传感器5", "传感器6"};
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this,
                android.R.layout.simple_spinner_item,
                options
        );
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
// 监听选择
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selected = options[position];
                if(position!=selectedSensorNum){
                    waveformViewX.clearDataPoints();
                    waveformViewY.clearDataPoints();
                    waveformViewZ.clearDataPoints();
                }
                selectedSensorNum=position;
               // Toast.makeText(OulajiaoActivity.this, "选择了: " + selectedSensorNum, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

    }

    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = new Intent(this, BluetoothService.class);
        intent.putExtra("DEVICE_ADDRESS", deviceId); // 如果需要
        bindService(intent, connection, Context.BIND_AUTO_CREATE);

    }

    @Override
    public void onDataProcessed(ProcessedData data) {
        String processedValue = data.getAngle();
        //  dataTextView.setText("收到数据: " + processedValue);
        String flag = data.getFlag();
        System.out.println("oulajiao-Flag:"+flag);
        System.out.println("oulajiao-Hex: " + processedValue);
        if(flag.equals("allout")){
            String[] dataArr = processedValue.split(" ");   // 按逗号分割
            switch(selectedSensorNum){
                case 0:
                    String da1 = dataArr[0].length()>10?dataArr[0].substring(0,8):dataArr[0];
                    String da2 = dataArr[1].length()>10?dataArr[1].substring(0,8):dataArr[1];
                    String da3 = dataArr[2].length()>10?dataArr[2].substring(0,8):dataArr[2];
//                    magxDataQueue.add(Float.parseFloat(da1));
//                    magyDataQueue.add(Float.parseFloat(da2));
//                    magzDataQueue.add(Float.parseFloat(da3));
                    waveformViewX.addDataPoint(Float.parseFloat(da1));
                    waveformViewY.addDataPoint(Float.parseFloat(da2));
                    waveformViewZ.addDataPoint(Float.parseFloat(da3));

                    break;
                case 1:
                    String dd1 = dataArr[3].length()>10?dataArr[3].substring(0,8):dataArr[3];
                    String dd2 = dataArr[4].length()>10?dataArr[4].substring(0,8):dataArr[4];
                    String dd3 = dataArr[5].length()>10?dataArr[5].substring(0,8):dataArr[5];

                    waveformViewX.addDataPoint(Float.parseFloat(dd1));
                    waveformViewY.addDataPoint(Float.parseFloat(dd2));
                    waveformViewZ.addDataPoint(Float.parseFloat(dd3));
                    break;
                case 2:
                    String de1 = dataArr[6].length()>10?dataArr[6].substring(0,8):dataArr[6];
                    String de2 = dataArr[7].length()>10?dataArr[7].substring(0,8):dataArr[7];
                    String de3 = dataArr[8].length()>10?dataArr[8].substring(0,8):dataArr[8];

                    waveformViewX.addDataPoint(Float.parseFloat(de1));
                    waveformViewY.addDataPoint(Float.parseFloat(de2));
                    waveformViewZ.addDataPoint(Float.parseFloat(de3));
                    break;
                case 3:
                    String df1 = dataArr[9].length()>10?dataArr[9].substring(0,8):dataArr[9];
                    String df2 = dataArr[10].length()>10?dataArr[10].substring(0,8):dataArr[10];
                    String df3 = dataArr[11].length()>10?dataArr[11].substring(0,8):dataArr[11];

                    waveformViewX.addDataPoint(Float.parseFloat(df1));
                    waveformViewY.addDataPoint(Float.parseFloat(df2));
                    waveformViewZ.addDataPoint(Float.parseFloat(df3));
                    break;
                case 4:
                    String dc1 = dataArr[12].length()>10?dataArr[12].substring(0,8):dataArr[12];
                    String dc2 = dataArr[13].length()>10?dataArr[13].substring(0,8):dataArr[13];
                    String dc3 = dataArr[14].length()>10?dataArr[14].substring(0,8):dataArr[14];

                    waveformViewX.addDataPoint(Float.parseFloat(dc1));
                    waveformViewY.addDataPoint(Float.parseFloat(dc2));
                    waveformViewZ.addDataPoint(Float.parseFloat(dc3));
                    break;
                case 5:
                    String db1 = dataArr[15].length()>10?dataArr[15].substring(0,8):dataArr[15];
                    String db2 = dataArr[16].length()>10?dataArr[16].substring(0,8):dataArr[16];
                    String db3 = dataArr[17].length()>10?dataArr[17].substring(0,8):dataArr[17];

                    waveformViewX.addDataPoint(Float.parseFloat(db1));
                    waveformViewY.addDataPoint(Float.parseFloat(db2));
                    waveformViewZ.addDataPoint(Float.parseFloat(db3));
                    break;
            }
//            startThreadx();
//            startThready();
//            startThreadz();
        }
    }
    /** 启动线程（只允许一个） */
    private void startThreadx() {
        if (workerThreadx != null && workerThreadx.isAlive()) {
            Log.d("Waveform", "线程已在运行，不重复创建");
            return;
        }

        runningx = true;
        workerThreadx = new Thread(() -> {
            Log.d("Waveform", "线程启动");
            while (runningx) {
                runOnUiThread(() -> {
                    if(!magxDataQueue.isEmpty()) {
                        waveformViewX.addDataPoint(magxDataQueue.poll());
                    }
                });
                try {
                    Thread.sleep(10); // 20ms 一次
                } catch (InterruptedException e) {
                    break;
                }
            }
            Log.d("Waveform", "线程退出");
        });
        workerThreadx.start();
    }
    /** 启动线程（只允许一个） */
    private void startThready() {
        if (workerThready != null && workerThready.isAlive()) {
            Log.d("Waveform", "线程已在运行，不重复创建");
            return;
        }
        runningy = true;
        workerThready = new Thread(() -> {
            Log.d("Waveform", "线程启动");
            while (runningy) {
                runOnUiThread(() -> {
                    if(!magyDataQueue.isEmpty()) {
                        waveformViewY.addDataPoint(magyDataQueue.poll());
                    }
                });
                try {
                    Thread.sleep(10); // 20ms 一次
                } catch (InterruptedException e) {
                    break;
                }
            }
            Log.d("Waveform", "线程退出");
        });
        workerThready.start();
    }
    /** 启动线程（只允许一个） */
    private void startThreadz() {
        if (workerThreadz != null && workerThreadz.isAlive()) {
            Log.d("Waveform", "线程已在运行，不重复创建");
            return;
        }
        runningz = true;
        workerThreadz = new Thread(() -> {
            Log.d("Waveform", "线程启动");
            while (runningz) {
                runOnUiThread(() -> {
                    if(!magzDataQueue.isEmpty()) {
                        waveformViewZ.addDataPoint(magzDataQueue.poll());
                    }
                });
                try {
                    Thread.sleep(10); // 20ms 一次
                } catch (InterruptedException e) {
                    break;
                }
            }
            Log.d("Waveform", "线程退出");
        });
        workerThreadz.start();
    }

    /** 停止线程 */
    private void stopThreads() {
        runningx = false;
        runningy = false;
        runningz = false;
        if (workerThreadx != null) {
            workerThreadx.interrupt();
            workerThreadx = null;
        }
        if (workerThready != null) {
            workerThready.interrupt();
            workerThready = null;
        }
        if (workerThreadz != null) {
            workerThreadz.interrupt();
            workerThreadz = null;
        }
        magxDataQueue.clear();
        magyDataQueue.clear();
        magzDataQueue.clear();
    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish(); // 结束当前Activity，返回上一个
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopThreads();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopThreads();
    }
}